package com.example.webbasic;

import java.util.Arrays;
import java.util.Date;
import java.util.function.Consumer;
import java.util.stream.IntStream;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
// 扫描使用了 @WebServlet 注解的Servlet类
@ServletComponentScan
@EnableAsync
public class WebBasicApplication {

	private static Consumer<Object> cs = System.out::println;

	public static void main(String[] args) {
		ConfigurableApplicationContext ctx = SpringApplication.run(WebBasicApplication.class, args);
		cs.accept("程序已启动");
		
//		studyContext(ctx);
		
		// 试验 启动异步线程
		CountNumber cn = (CountNumber) ctx.getBean("countNumber");
		cs.accept("CountNumber cn=" + cn);
		cn.pn();
		
		cs.accept("main 结束");
	}
	
	@Autowired
	private HttpServletRequest req;
	
	@Autowired
	private HttpServletResponse resp;
	
	public static void studyContext(ConfigurableApplicationContext ctx) {
		cs.accept("++++++studyContext++++++\nBeanDefinitionCount=" + ctx.getBeanDefinitionCount());
		String[] beanNames = ctx.getBeanDefinitionNames();
		cs.accept("beanNames.length=" + beanNames.length);
		cs.accept("输出Bean的名称：");
		Arrays.stream(beanNames).forEach((name)->{
			cs.accept("session name=" + name);
		});

		cs.accept("++++++studyContext 结束++++++");
	}
	
}

/**
 * springboot中@EnableAsync与@Async注解使用
 * https://www.cnblogs.com/UniqueColor/p/9295642.html
 * \@EnableAsync与\@Async 一起使用才有效！
 * @author ben
 * @date 2021-11-07 16:38:13 CST
 */
@Component
class CountNumber {
	
	// 开启异步操作
	@Async
	public void pn() {
		String tn = Thread.currentThread().getName();
		IntStream.range(0, 10).forEach(e->{
			System.out.println(tn + ": e=" + e);
		});
	}
}
